package com.g2room.driving.grap.article;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.g2room.driving.grap.GenericGrap;
import com.g2room.driving.grap.article.to.ImgTo;
import com.g2room.driving.util.DbUtil;
import com.g2room.driving.util.ImageUtil;

public class HandleImages {
	static String baseUrl = "http://www.checar.cn";
	public static List<ImgTo> imgSrcs = new ArrayList<ImgTo>();
//	private static Map<String, Boolean> imgMap = new HashMap<String, Boolean>();
//	static List<String> imageSqls = GenericGrap.getImgData(null);
	public static void main(String[] args) {
		getImgs(null, null);
	}
	
	public static void getImgs(List<Integer> ids, String url) {
		if(null != url) baseUrl = url;
		System.out.println("准备抓取数据：" + ids.toString());
		getImageSrc(ids);
		StringBuffer errSrcSb = new StringBuffer();
		for(ImgTo img : imgSrcs) {
			String src = img.getGrapSrc();
			if(!src.startsWith("http://") || src.startsWith("http://b.bshare.cn/barCode") 
					|| src.equals("http://a.img16888.com/common/sprite.gif") 
					|| src.startsWith("http://www.g2room.com/images/")
					|| src.contains("kaichejiqiao.cn")
					|| src.contains("wine22.com")
//					|| (null != imgMap.get(src))
					) {
				continue;
			}
			System.out.println("抓取====="+src);
			try {
				String filePath = ImageUtil.downloadImage(src, img.getTypeName());
				insertImg("update d_article_grap set content=replace(content,'"+img.getOldSrc()+"','"+filePath.replace(ImageUtil.folder, "http://www.kaichejiqiao.cn/images/")+"');");
			} catch (Exception e) {
				System.out.println(src + "\n");
				e.printStackTrace();
			}
		}
		DbUtil.closeConn();
		// 生成update语句
		System.out.println(errSrcSb.toString());
	}
	
	/**
	 * 获取所有的图片地址
	 */
	public static void getImageSrc(List<Integer> ids) {
		try {
			String idsSql = "";
			if(null == ids || ids.size() == 0) return;
			for(Integer id: ids) {
				if(idsSql.length() > 0) idsSql += ",";
				idsSql += id;
			}
			System.out.println("img数据ids：" + idsSql);
			if(idsSql.length() > 0) idsSql = " id in (" + idsSql + ") ";
			Connection connection = DbUtil.getConn();
			Statement statement = connection.createStatement();
//			String sql = "select category_name,source,content from d_article_grap where state=2 and category_name ='待处理'";
//			String sql = "select category_name,source,content from d_article_grap where state=2 and category_name <>'待处理'";
//			String sql = "select category_name,source,content from d_article_grap where state=9 and category_name ='待处理'";
//			String sql = "select category_name,source,content from d_article_grap where state=9 and category_name <>'待处理'";
			String sql = "select type_name,source,content from d_article_grap where " + idsSql;
			ResultSet rs = statement.executeQuery(sql);
			rs.last();
			System.out.println(rs.getRow());
			rs.first();
			while(rs.next()) {
				String content = rs.getString("content");
				String typeName = rs.getString("type_name");
				// 提取src值
				List<String> imgs = ImageUtil.getImgSrc(content);
				boolean imgExist = false;
				for(String src : imgs) {
					if(src.contains("kaichejiqiao.cn")) continue;
					ImgTo it = new ImgTo();
					it.setOldSrc(src);
					
					src = src.replaceAll("&amp;", "&");
					src = (src.startsWith("http://")?src : baseUrl + (src.contains("../../../")?src.replace("../../..", "") : src));
					it.setGrapSrc(src.replaceAll(" ", "%20"));
//					src = (src.contains("../../../")?baseUrl + src.replace("../../..", "") : src);
//					// 判断是否存在
//					for(String imageSql : imageSqls) {
//						if(imageSql.contains(src)) {
//							imgExist = true;
//							break;
//						}
//					}
					it.setTypeName(typeName);
					// 不存在才去抓取
					if(!imgExist) imgSrcs.add(it);
				}
			}
			rs.close();
			statement.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void insertImg(String sql) {
		try {
			Connection connection = DbUtil.getConn();
			PreparedStatement statement = connection.prepareStatement("insert into d_images(updateSql) values(?)");
			statement.setString(1, sql);
			statement.execute();
			statement.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
